package com.fulihui.wgj.auth.controller;

import com.fulihui.common.enums.WxAuthReturnEnum;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.wgj.auth.config.WxIssueConfig;
import com.fulihui.wgj.auth.service.WeixinIssueTestService;
import com.fulihui.wgj.auth.service.WxEventService;
import com.fulihui.wgj.auth.vo.NotifyVO;
import com.fulihui.wgj.facade.request.event.AuthNotifyRequest;
import com.fulihui.wgj.facade.request.event.EventNotifyRequest;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * 微信平台事件监听
 * Created by LeeSon on 2017/3/30 0030.
 */
@Controller
public class WxEventController {
    private static final Logger logger  = LoggerFactory.getLogger(WxEventController.class);

    @Resource
    WeixinIssueTestService weixinIssueTestBiz;

    @Resource
    private WxIssueConfig wxIssueConfig;

    @Autowired
    WeixinSDK weixinSDK;

    @Autowired
    WxEventService wxEventService;

    /**
     * 授权事件接收URL
     * @param form
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/authNotify", method = RequestMethod.POST)
    @ResponseBody
    public String authNotify(NotifyVO form, HttpServletRequest request) throws Exception {
        try {
            String postData = IOUtils.toString(request.getInputStream(), "UTF-8");

            logger.info("授权消息处理 ----> Post消息数据:"+postData);

            AuthNotifyRequest authNotifyRequest = new AuthNotifyRequest();
            BeanUtils.copyProperties(form, authNotifyRequest);
            authNotifyRequest.setPostDate(postData);

            wxEventService.authNotify(authNotifyRequest);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return WxAuthReturnEnum.SUCCESS.getDesc();
    }

    /**
     * 公众号消息与事件接收URL
     * @param appId
     * @param form
     * @param request
     * @return
     */
    @RequestMapping(value = "/{appId}/eventNotify")
    @ResponseBody
    public String eventNotify(@PathVariable("appId") String appId, NotifyVO form, HttpServletRequest request) {
        try {
            String postData = IOUtils.toString(request.getInputStream(), "UTF-8");

            logger.info("事件消息处理 ----> Post消息数据:"+postData);

            EventNotifyRequest eventNotifyRequest = new EventNotifyRequest();
            BeanUtils.copyProperties(form, eventNotifyRequest);
            eventNotifyRequest.setAppId(appId);
            eventNotifyRequest.setPostDate(postData);

            //TODO 微信开放平台全网发布检测专用，微管家已经申请通过全网发布，代码请保留
            if(wxIssueConfig.getWxTestMpAppId().equals(appId)){
                logger.info("微信全网发布检测执行........");
                return weixinIssueTestBiz.issueTest(eventNotifyRequest);
            }

            wxEventService.eventNotify(eventNotifyRequest);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return WxAuthReturnEnum.SUCCESS.getDesc();
    }

    /**
     * 预授权引导，跳转到微信预授权页面
     * @param loginId 微管家后台用户登录账户
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/preAuth/{loginId}", method = RequestMethod.GET)
    public String preAuth(@PathVariable("loginId") String loginId, HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {

        //获取认证Url
        String preAuthUrl = wxEventService.preAuthUrl(loginId);

        return "redirect:"+(preAuthUrl==null?"":preAuthUrl);
    }

    /**
     * 微信回调地址
     * @param map
     * @param request
     * @param auth_code
     * @return
     */
    @RequestMapping(value = "/authCallBack", method = RequestMethod.GET)
    public String authCallBack(ModelMap map, HttpServletRequest request, String auth_code) {
        Assert.notNull(auth_code, "授权码不能为空.");

        boolean success = wxEventService.authCallBack(auth_code);

        return success ? wxIssueConfig.getWgjManageRedirectUrl() : "/";
    }

}
